import fs from "node:fs";
import fetch from "node-fetch";

export class example2 extends plugin {
  constructor() {
    super({
      name: "发送消息",
      dsc: "主人测试发送消息",
      event: "message",
      priority: 5000,
      rule: [
        {
          reg: "^#发送?视频",
          fnc: "SendVideo",
          permission: "master",
        },
        {
          reg: "^#发送?图片",
          fnc: "SendImage",
          permission: "master",
        },
      ],
    });
  }

  async SendVideo(e) {
    try {
      const url = e.msg.replace("#发送视频", "").trim();
      if (!url) {
        await e.reply('请输入视频 URL。');
        return;
      }

      await e.reply('正在下载视频...');

      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`获取视频失败: ${response.statusText}`);
      }

      const buffer = await response.arrayBuffer();
      const filePath = `${process.cwd()}/resources/test.mp4`;

      await fs.promises.writeFile(filePath, Buffer.from(buffer), 'binary');
      await e.reply("视频保存成功，开始上传视频...");

      const res = await e.reply(segment.video(filePath));
      if (!res) return e.reply("视频发送失败！请检查控制台日志");
      
    } catch (err) {
      await e.reply(`下载或保存视频时出错: ${err.message}`);
    }
  }

  async SendImage(e) {
    try {
      const url = e.msg.replace("#发送图片", "").trim();
      if (!url) {
        await e.reply('请输入图片 URL。');
        return;
      }

      await e.reply('正在下载图片...');

      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`获取图片失败: ${response.statusText}`);
      }

      const buffer = await response.arrayBuffer();
      const filePath = `${process.cwd()}/resources/test.png`;

      await fs.promises.writeFile(filePath, Buffer.from(buffer), 'binary');
      await e.reply("图片保存成功，开始上传图片...");

      const res = await e.reply(segment.image(filePath));
      if (!res) return e.reply("图片发送失败！请检查控制台日志");
      
    } catch (err) {
      await e.reply(`下载或保存图片时出错: ${err.message}`);
    }
  }
}